package com.example.smartpark.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.smartpark.dto.AnnouncementCategoryDTO;
import com.example.smartpark.exception.BusinessException;
import com.example.smartpark.mapper.AnnouncementCategoryMapper;
import com.example.smartpark.mapper.AnnouncementMapper;
import com.example.smartpark.model.Announcement;
import com.example.smartpark.model.AnnouncementCategory;
import com.example.smartpark.service.AnnouncementCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 公告分类Service实现类
 */
@Slf4j
@Service
public class AnnouncementCategoryServiceImpl extends ServiceImpl<AnnouncementCategoryMapper, AnnouncementCategory> implements AnnouncementCategoryService {

    @Autowired
    private AnnouncementMapper announcementMapper;

    @Override
    public List<AnnouncementCategoryDTO> getAllCategories() {
        // 查询所有启用的分类
        LambdaQueryWrapper<AnnouncementCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AnnouncementCategory::getStatus, 1)
                .orderByAsc(AnnouncementCategory::getSortOrder);
        List<AnnouncementCategory> categories = this.list(queryWrapper);
        
        // 转换为DTO
        return categories.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    public IPage<AnnouncementCategoryDTO> getCategoryPage(int page, int size) {
        // 分页查询
        Page<AnnouncementCategory> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<AnnouncementCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(AnnouncementCategory::getSortOrder);
        IPage<AnnouncementCategory> categoryPage = this.page(pageParam, queryWrapper);
        
        // 转换为DTO
        return categoryPage.convert(this::convertToDTO);
    }

    @Override
    public AnnouncementCategoryDTO getCategoryById(Integer id) {
        // 查询分类
        AnnouncementCategory category = this.getById(id);
        if (category == null) {
            throw new BusinessException("公告分类不存在");
        }
        
        // 转换为DTO
        return convertToDTO(category);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AnnouncementCategoryDTO createCategory(AnnouncementCategoryDTO categoryDTO) {
        // 检查名称是否已存在
        LambdaQueryWrapper<AnnouncementCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AnnouncementCategory::getName, categoryDTO.getName());
        if (this.count(queryWrapper) > 0) {
            throw new BusinessException("分类名称已存在");
        }
        
        // 设置默认值
        if (categoryDTO.getSortOrder() == null) {
            categoryDTO.setSortOrder(0);
        }
        if (categoryDTO.getStatus() == null) {
            categoryDTO.setStatus(1); // 默认启用
        }
        
        // 转换为实体
        AnnouncementCategory category = new AnnouncementCategory();
        BeanUtils.copyProperties(categoryDTO, category);
        
        // 保存
        this.save(category);
        
        // 返回DTO
        return convertToDTO(category);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AnnouncementCategoryDTO updateCategory(Integer id, AnnouncementCategoryDTO categoryDTO) {
        // 验证分类是否存在
        AnnouncementCategory category = this.getById(id);
        if (category == null) {
            throw new BusinessException("公告分类不存在");
        }
        
        // 检查名称是否已存在（排除自身）
        if (categoryDTO.getName() != null && !categoryDTO.getName().equals(category.getName())) {
            LambdaQueryWrapper<AnnouncementCategory> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AnnouncementCategory::getName, categoryDTO.getName());
            if (this.count(queryWrapper) > 0) {
                throw new BusinessException("分类名称已存在");
            }
        }
        
        // 更新属性
        if (categoryDTO.getName() != null) {
            category.setName(categoryDTO.getName());
        }
        if (categoryDTO.getDescription() != null) {
            category.setDescription(categoryDTO.getDescription());
        }
        if (categoryDTO.getSortOrder() != null) {
            category.setSortOrder(categoryDTO.getSortOrder());
        }
        if (categoryDTO.getStatus() != null) {
            category.setStatus(categoryDTO.getStatus());
        }
        
        // 保存
        this.updateById(category);
        
        // 返回DTO
        return convertToDTO(category);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCategory(Integer id) {
        // 验证分类是否存在
        AnnouncementCategory category = this.getById(id);
        if (category == null) {
            throw new BusinessException("公告分类不存在");
        }
        
        // 检查是否有公告使用该分类
        LambdaQueryWrapper<Announcement> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Announcement::getCategoryId, id);
        if (announcementMapper.selectCount(queryWrapper) > 0) {
            throw new BusinessException("该分类下有公告，无法删除");
        }
        
        // 删除分类
        return this.removeById(id);
    }

    /**
     * 将实体转换为DTO
     *
     * @param category 分类实体
     * @return 分类DTO
     */
    private AnnouncementCategoryDTO convertToDTO(AnnouncementCategory category) {
        if (category == null) {
            return null;
        }
        
        AnnouncementCategoryDTO dto = new AnnouncementCategoryDTO();
        BeanUtils.copyProperties(category, dto);
        return dto;
    }
} 